package com.moma.chatting.core;

import java.util.HashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.moma.chatting.exception.*;

public class MessageDispatcher implements Runnable {
	private BlockingQueue<Message> messages;
	private HashMap<Integer, Conversation> conversationMap;
	private final static Logger logger;
	
	static{
		logger = LoggerFactory.getLogger(MessageDispatcher.class);
	}
	
	public MessageDispatcher(BlockingQueue<Message> messages,
			HashMap<Integer, Conversation> conversationMap){
		this.messages = messages;
		this.conversationMap = conversationMap;
	}
	
	public void run() {
		logger.info("Dispatcher started...");
		while (true){
			try {
				Message msg = messages.take();
				int conversationId = msg.getConversationId();
				synchronized(this.conversationMap){
					Conversation conv = conversationMap.get(conversationId);
					if (conv == null){
						logger.info(String.format("Conversation %d is not exists...", conversationId));
						continue;
					}
					logger.info("add message to history");
					conv.addToHistory(msg);
					for(User user : conv.getGroup().getAllUsers()){
						try{
						conv.dispatchMessage(user.getUniqueName(), msg);
						logger.info(String.format("Push message to %s", user.getUniqueName()));
						} catch (UserExpiredException e){
							logger.error(String.format("User %s is expired, dispatch message failed...", user.getUniqueName()));
						}
					}
				}

			}
			catch (Exception e) {
				logger.error("Dispatcher throws exception..." + e.toString());
			}
		}
	}
}
